import React, {
    Component
} from 'react';

import {
    StyleSheet,
    Text,
    TouchableWithoutFeedback,
    View,
    Button,
    BackHandler
} from 'react-native';

import Video from 'react-native-video';
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { pTx } from "../../utils/dimensions"
import httpApi from "../../api"



function formatTime(second) {
    let h = 0, i = 0, s = parseInt(second);
    if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
    }
    // 补零
    let zero = function (v) {
        return (v >> 0) < 10 ? "0" + v : v;
    };
    console.log([zero(h), zero(i), zero(s)].join(":"));
    // return [zero(h), zero(i), zero(s)].join(":");
    return zero(s);
}

export default class VideoScreen extends Component {

    static navigationOptions = {
        header: null
    };


    state = {
        rate: 1,
        volume: 1,
        muted: false,
        resizeMode: 'contain',
        duration: 0.0,
        currentTime: 0.0,
        paused: false,
        M: this.props.route.params.M?.split(' ')
    };

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }

    onBackAndroid = () => {
        this.props.navigation.goBack();
        return true;
    };


    onLoad = (data) => {
        this.setState({ duration: data.duration });
        console.log(data.duration + "xxx");
    };

    onProgress = (data) => {
        this.setState({ currentTime: data.currentTime });
        console.log(data.currentTime + "hhh");
    };

    onEnd = () => {
        this.setState({ paused: true })
        this.video.seek(0)
    };

    onAudioBecomingNoisy = () => {
        this.setState({ paused: true })
    };

    onAudioFocusChanged = (event) => {
        this.setState({ paused: !event.hasAudioFocus })
    };

    getCurrentTimePercentage() {
        if (this.state.currentTime > 0) {
            return parseFloat(this.state.currentTime) / parseFloat(this.state.duration);
        }
        return 0;
    };

    renderRateControl(rate) {
        const isSelected = (this.state.rate === rate);

        return (
            <TouchableWithoutFeedback onPress={() => {
                this.setState({ rate })
            }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {rate}x
                </Text>
            </TouchableWithoutFeedback>
        );
    }

    renderResizeModeControl(resizeMode) {
        const isSelected = (this.state.resizeMode === resizeMode);

        return (
            <TouchableWithoutFeedback onPress={() => {
                this.setState({ resizeMode })
            }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {resizeMode}
                </Text>
            </TouchableWithoutFeedback>
        )
    }

    renderVolumeControl(volume) {
        const isSelected = (this.state.volume === volume);
        return (
            <TouchableWithoutFeedback onPress={() => {
                this.setState({ volume })
            }}>
                <Text style={[styles.controlOption, { fontWeight: isSelected ? 'bold' : 'normal' }]}>
                    {volume * 100}%
                </Text>
            </TouchableWithoutFeedback>
        )
    }

    render() {
        const flexCompleted = this.getCurrentTimePercentage() * 100;
        const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100;

        return (
            <View style={styles.container}>
                <TouchableWithoutFeedback
                    style={styles.fullScreen}
                    onPress={() => this.setState({ paused: !this.state.paused })}>
                    <Video
                        ref={(ref) => {
                            this.video = ref
                        }}
                        /* For ExoPlayer */
                        source={{ uri: (this.state.M[1].slice(0, 4) != "file" ? httpApi.inline : "") + this.state.M[1] }}
                        style={styles.fullScreen}
                        rate={this.state.rate}
                        paused={this.state.paused}
                        volume={this.state.volume}
                        muted={this.state.muted}
                        resizeMode={this.state.resizeMode}
                        onLoad={this.onLoad}
                        onProgress={this.onProgress}
                        onEnd={this.onEnd}
                        onAudioBecomingNoisy={this.onAudioBecomingNoisy}
                        onAudioFocusChanged={this.onAudioFocusChanged}
                        repeat={false}
                    />
                </TouchableWithoutFeedback>
                <View style={styles.textStyle}>
                    <TouchableWithoutFeedback hitSlop={{ top: 10, left: 10, bottom: 10, right: 10 }} onPress={() => {
                        this.props.navigation.goBack()
                    }}>
                        <View style={styles.btnStyle}>
                            <IconOutline style={styles.left} name="close-circle" />
                        </View>
                    </TouchableWithoutFeedback>

                    <Text style={styles.volumeControl}>
                        {formatTime(this.state.duration - this.state.currentTime)}
                    </Text>
                </View>

                <View style={styles.controls}>
                    <View style={styles.generalControls}>
                    </View>
                    <View style={styles.trackingControls}>
                        <View style={styles.progress}>
                            <View style={[styles.innerProgressCompleted, { flex: flexCompleted }]} />
                            <View style={[styles.innerProgressRemaining, { flex: flexRemaining }]} />
                        </View>
                    </View>
                </View>
                {
                    this.state.paused &&
                    <View style={styles.playCircleBox} >
                        <TouchableWithoutFeedback onPress={() => this.setState({ paused: !this.state.paused })}>
                            <IconOutline style={styles.playCircle} name="play-circle" />
                        </TouchableWithoutFeedback>
                    </View>
                }

            </View>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        position: "relative",
        flex: 1,
        backgroundColor: 'black',
    },
    textStyle: {
        paddingHorizontal: 10,
        paddingTop: 25,
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between",
    },
    btnStyle: {
    },
    left: {
        fontSize: 25,
        color: '#fff',
    },
    volumeControl: {
        fontSize: 12,
        color: '#fff',
    },
    fullScreen: {
        position: 'absolute',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
    },
    controls: {
        backgroundColor: 'transparent',
        borderRadius: 5,
        position: 'absolute',
        bottom: 20,
        left: 20,
        right: 20,
    },
    progress: {
        flex: 1,
        flexDirection: 'row',
        borderRadius: 3,
        overflow: 'hidden',
    },
    innerProgressCompleted: {
        height: 2,
        backgroundColor: '#cccccc',
    },
    innerProgressRemaining: {
        height: 2,
        backgroundColor: '#2C2C2C',
    },
    generalControls: {
        flex: 1,
        flexDirection: 'row',
        borderRadius: 4,
        overflow: 'hidden',
        paddingTop: 10,
    },
    rateControl: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
    },

    resizeModeControl: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    controlOption: {
        alignSelf: 'center',
        fontSize: 11,
        color: 'white',
        paddingLeft: 2,
        paddingRight: 2,
        lineHeight: 12,
    },
    playCircleBox: {
        position: "absolute",
        flex: 1,
        left: 0,
        right: 0,
        bottom: 0,
        top: 0,
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center",
    },
    playCircle: {
        fontSize: pTx(50),
        color: "#fff",
    }
});